package MyFragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;

import com.qb.devtest.MyApplication;
import com.qb.devtest.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import utils.DevInfoUtil;
import utils.MyUtil;

public class FragmentBluetooth extends Fragment {
    public TextView tvBtTitle,tvBtName,tvBtVersion,tvBtMac;
    Context ctx = MyApplication.getInstance();
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Discovery has found a device
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                MyUtil.showLog("mReceiver", device);
                MyUtil.showLog("mReceiver getAddress="+device.getAddress(),"");
                if (ActivityCompat.checkSelfPermission(ctx, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    MyUtil.showLog("mReceiver getName="+device.getName(), "");
                    MyUtil.showLog("mReceiver getType="+device.getType(),"");
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                        MyUtil.showLog("mReceiver getAlias="+device.getAlias(),"");
                    }
                    MyUtil.showLog("mReceiver getBondState="+device.getBondState(),"");
                    return;
                } else {
                    MyUtil.showLog("mReceiver", "没有BLUETOOTH_CONNECT权限");
                }

            }
        }
    };
    BluetoothAdapter mBluetoothAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_bluetooth, container, false);
        tvBtTitle = view.findViewById(R.id.tv_bt_title);
        tvBtName = view.findViewById(R.id.tv_bt_name);
        tvBtVersion = view.findViewById(R.id.tv_bt_version);
        tvBtMac = view.findViewById(R.id.tv_bt_mac);

        tvBtTitle.setText("");
        tvBtName.setText("");
        tvBtVersion.setText("");
        tvBtMac.setText("");

        Button btnCopy = view.findViewById(R.id.btn_copy);
        btnCopy.setOnClickListener(view1 -> {
            String n = String.valueOf(tvBtName.getText());
            String v = String.valueOf(tvBtVersion.getText());
            String m = String.valueOf(tvBtMac.getText());
            MyUtil.copyStr(ctx, n+m+"\n");
        });

        loadData();
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 在这里初始化你的Fragment视图组件
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (ActivityCompat.checkSelfPermission(ctx, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mBluetoothAdapter.cancelDiscovery();
    }

    public void loadData() {
        JSONObject btInfo = DevInfoUtil.getBleInfo(ctx);
        String name = "unKnow";
        String mac = "unKnow";
        String version = "unKnow";
        try {
            name = btInfo.getString("name");
            mac = btInfo.getString("mac");
            version = btInfo.getString("version");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String btName = "   蓝牙名称：" + name + "   版本：" + version + "   MAC地址：" + mac;
//        tvBtName.setText(btName);

        tvBtTitle.setText(name.equals("unKnow")?"  请允许开启蓝牙权限":"  蓝牙信息获取成功");
        tvBtName.setText("  本机蓝牙名称  " + name);
        tvBtVersion.setText("  版本  "+version);
        tvBtMac.setText("  MAC地址  "+mac);

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            // 设备不支持蓝牙
            Drawable drawable = ctx.getResources().getDrawable(R.drawable.ic_baseline_close_24);
            drawable.setBounds(0, 0, 24, 24);
            tvBtTitle.setCompoundDrawables(drawable, null, null, null);
            tvBtTitle.setText(" 当前设备不支持蓝牙");
        }
        if (mBluetoothAdapter.isEnabled()) {
            if (ActivityCompat.checkSelfPermission(ctx, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            //mBluetoothAdapter.startDiscovery();
        } else {
            // 蓝牙未开启，提示用户开启
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
        }
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        ctx.registerReceiver(mReceiver, filter);
    }
}